'use client';

import Link, { LinkProps } from 'next/link';
import { PropsWithChildren, forwardRef, CSSProperties, useEffect, useState } from 'react';

interface HtmlLinkProps extends LinkProps, PropsWithChildren {
  className?: string;
  id?: string;
  style?: CSSProperties;
}

const HtmlLink = forwardRef<HTMLAnchorElement, HtmlLinkProps>(
  ({ href, children, className, id, style, ...props }, ref) => {
    // 处理href，添加.html后缀
    let htmlHref = href;
    
    // 用于跟踪窗口尺寸
    const [isLargeScreen, setIsLargeScreen] = useState(false);
    
    // 监听窗口尺寸变化
    useEffect(() => {
      const checkScreenSize = () => {
        setIsLargeScreen(window.innerWidth >= 768); // 768px 作为大屏幕的断点
      };
      
      // 初始检查
      checkScreenSize();
      
      // 监听窗口尺寸变化
      window.addEventListener('resize', checkScreenSize);
      
      // 清理事件监听
      return () => window.removeEventListener('resize', checkScreenSize);
    }, []);
    
    // 判断是否为详情页链接
    let isDetailPage = false;
    
    if (typeof href === 'string') {
      // 分离路径和查询参数
      const [path, query] = href.split('?');
      
      // 检查是否为详情页链接（以/detail开头）
      isDetailPage = path.startsWith('/detail');
      
      // 如果href已经包含.html后缀或者是特殊路径，则不做修改
      if (!path.endsWith('.html') && 
          !path.includes('.') && 
          !path.startsWith('/_next') &&
          !path.startsWith('/api')) {
        
        // 首页路径保持不变，使用 /
        if (path === '/') {
          htmlHref = '/';
        } else if (path.endsWith('/')) {
          htmlHref = `${path}index.html${query ? `?${query}` : ''}`;
        } else {
          htmlHref = `${path}.html${query ? `?${query}` : ''}`;
        }
      }
    }

    // 根据屏幕尺寸和链接类型决定是否在新标签打开
    const target = isDetailPage && isLargeScreen ? '_blank' : undefined;
    const rel = target === '_blank' ? 'noopener noreferrer' : undefined;

    return (
      <Link 
        href={htmlHref} 
        className={className} 
        id={id} 
        style={style} 
        ref={ref} 
        target={target}
        rel={rel}
        {...props}
      >
        {children}
      </Link>
    );
  }
);

HtmlLink.displayName = 'HtmlLink';

export default HtmlLink; 